package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.SORT_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate redis;
    @Override
    public List<ShopType> queryOrderBySortAsc() {
        //1.去redis中查询类型
        List<String> temp = redis.opsForList().range(SORT_SHOP_KEY, 0, -1);
        //2.查到直接返回，注意是把集合里的数据转成json存储。其实也可以整个，见网上解决方案
        if(!temp.isEmpty()) {
            List<ShopType> types = new ArrayList<>(temp.size());
            for (String typesJson : temp) {
                ShopType bean = JSONUtil.toBean(typesJson, ShopType.class);
                types.add(bean);
            }
            return types;
        }
        //3.没查到，去数据库查询
        List<ShopType> types = query().orderByAsc("sort").list();
        //4.没查到，返回404
        if(types.isEmpty()){
            return null;
        }
        //5.查到，保存在redis中
        for (ShopType type : types) {
            String bean = JSONUtil.toJsonStr(type);
            temp.add(bean);
        }
        redis.opsForList().rightPushAll(SORT_SHOP_KEY, temp);
        //6.返回
        return types;
    }
}
